package com.demarc.pesquisas.web.jsf;

import java.util.Map;

import javax.faces.context.FacesContext;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

public class ViewScope implements Scope {

	@Override
	public Object get(String name, ObjectFactory objectFactory) {
		Map<String, Object> viewMap = FacesContext.getCurrentInstance()
				.getViewRoot().getViewMap();

		if (viewMap.containsKey(name)) {
			Object bean = viewMap.get(name);

			// restore a transient autowired beans after re-serialization bean
			WebApplicationContext webAppContext = ContextLoader
					.getCurrentWebApplicationContext();
			AutowireCapableBeanFactory autowireFactory = webAppContext
					.getAutowireCapableBeanFactory();

			if (webAppContext.containsBean(name)) {
				// Reconfigure resored bean instance.
				bean = autowireFactory.configureBean(bean, name);
			}
			// end restore

			return bean;
		} else {
			Object object = objectFactory.getObject();
			viewMap.put(name, object);

			return object;
		}
	}

	@Override
	public Object remove(String name) {
		return FacesContext.getCurrentInstance().getViewRoot().getViewMap()
				.remove(name);
	}

	@Override
	public String getConversationId() {
		return null;
	}

	@Override
	public void registerDestructionCallback(String name, Runnable callback) {
		// Not supported
	}

	@Override
	public Object resolveContextualObject(String key) {
		return null;
	}
}